<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JavaScript Drum Kit</title>
    <link rel="stylesheet" href="./styles.css">
</head>
<body>
    <div class="keys">
        <div data-key="65" class="key">
            <kbd>A</kbd>
            <span class="sound">clap</span>
        </div>
        <div data-key="83" class="key">
            <kbd>S</kbd>
            <span class="sound">hihat</span>
        </div>
        <div data-key="68" class="key">
            <kbd>D</kbd>
            <span class="sound">kick</span>
        </div>
        <div data-key="70" class="key">
            <kbd>F</kbd>
            <span class="sound">openhat</span>
        </div>
        <div data-key="71" class="key">
            <kbd>G</kbd>
            <span class="sound">boom</span>
        </div>
        <div data-key="72" class="key">
            <kbd>H</kbd>
            <span class="sound">ride</span>
        </div>
        <div data-key="74" class="key">
            <kbd>J</kbd>
            <span class="sound">snare</span>
        </div>
        <div data-key="75" class="key">
            <kbd>K</kbd>
            <span class="sound">tom</span>
        </div>
        <div data-key="76" class="key">
            <kbd>L</kbd>
            <span class="sound">tink</span>
        </div>
    </div>

    <audio data-key="65" src="sounds/clap.wav"></audio>
    <audio data-key="83" src="sounds/hihat.wav"></audio>
    <audio data-key="68" src="sounds/kick.wav"></audio>
    <audio data-key="70" src="sounds/openhat.wav"></audio>
    <audio data-key="71" src="sounds/boom.wav"></audio>
    <audio data-key="72" src="sounds/ride.wav"></audio>
    <audio data-key="74" src="sounds/snare.wav"></audio>
    <audio data-key="75" src="sounds/tom.wav"></audio>
    <audio data-key="76" src="sounds/tink.wav"></audio>

<script>
    function removeTransition(event) {
        if(event.propertyName !== "transform") return; // 如果样式未发生变化，则就此跳出函数，即过滤
        event.target.classList.remove("playing"); // 移除高亮的样式
    }

    function playSound(event) {
        const audio = document.querySelector(`audio[data-key="${event.keyCode}"]`); // 根据触发按键的键码，获取对应音频
        const key = document.querySelector(`div[data-key="${event.keyCode}"]`) // 获取页面对应按钮 DIV 元素
        if(!audio) return; // 处理无效的按键事件

        key.classList.add("playing"); // 改变样式
        audio.currentTime = 0; // 每次播放之后都使音频播放进度归零
        audio.play(); // 播放相应音效
    }

    const keys = Array.from(document.querySelectorAll('.key')); // 获取页面所有按钮元素

    keys.forEach(key => key.addEventListener("transitionend", removeTransition)); // 遍历每一个 .key 元素；添加 transitionend 事件监听，transitionend 事件会在 CSS transition 结束后触发，从而调用 removeTransition 函数

    window.addEventListener("keydown", playSound); // 添加键盘 keydown 事件，当按下某一个键时，会触发 keydown 事件，从而调用 playSound 函数，播放对应音效
</script>

</body>
</html>
